﻿/*
 * slaver104.cpp
 *
 *  Created on: 2017年5月14日
 *      Author: work
 */

#include <iostream>
#include <boost/program_options.hpp>
#include <dm/os/protocol/protocolcontrolor.hpp>
#include <dm/os/protocol/protocollistenor.hpp>
#include <dm/os/ascom/tcplistner.hpp>
#include <dm/os/ascom/tcpclientdevice.hpp>
#include <dm/os/sys/taskagent.hpp>
#include "dm104slaver.h"
#include <dm/os/msg/msgdriver.hpp>

using namespace std;
using namespace boost::program_options;

using namespace dm::os;

int main( int argc,char* argv[] ){
	options_description desc("DM104从站");
	desc.add_options()
			("help,h","显示本帮助信息")
			("version,v","显示版本及编译信息")
			("test","测试模式运行")
			("ip",value<string>(),"ip")
			("port",value<int>(),"端口")
			;

	variables_map vm;
	try{
		store(parse_command_line(argc,argv,desc),vm);
		notify(vm);
	}catch( std::exception& ex ){
		cout << ex.what()<<endl;
		return 1;
	}

	if( vm.count("version") ){
		cout <<"V1.0 构建于 "<<__DATE__<<endl;
		return 1;
	}

	if( vm.count("help") ){
		cout <<desc<<endl;
		return 1;
	}

	com::ios_t ios;

	protocol::CProtocolListenor* listner = new protocol::CProtocolListenor;

	ascom::CTcpListner* port = new ascom::CTcpListner(ios);

	com::CTcpServerAddr address;
	if( vm.count("ip") )
		address.setLocalHost(vm["ip"].as<string>().c_str());
	else
		address.setLocalHost("0.0.0.0");

	if( vm.count("port") )
		address.setLocalPort(vm["port"].as<int>());
	else
		address.setLocalPort(2404);

	dm::os::sys::CTaskAgent* taskAgent = NULL;

	if( !vm.count("test") )
		taskAgent = new dm::os::sys::CTaskAgent(argc,argv);

	port->setAddress(address);

	listner->setListenor( port );

	protocol::CProtocolControlor* controlor = new protocol::CProtocolControlor(ios);

	CDm104Slaver* protocolDm = new CDm104Slaver;
	controlor->setProtocol(protocolDm);

	listner->addProtocolControlor(controlor);

	listner->startListen();

	if( taskAgent ){
		com::CTimer timer(ios);
		timer.start_seconds(true,10);
		while( taskAgent->runOnce() ){
			ios.run_one();

			if( controlor->isExiting() )
				break;
		}

		delete taskAgent;
	}else{
		ios.run();
	}

	return 0;
}


